﻿/**
 * ...
 * @author Артём Григорьев
 */

package loader;
import client.Channel;
import client.Item;

class ChannelXmlParser 
{
	private var xml : Xml;

	public function new(xml : Xml) 
	{
		this.xml = xml;
	}
	
	public function parse() : Array<Channel>
	{
		
		var channelsArray = new Array<Channel>();
				
		var responseIterator = xml.iterator();
		if (responseIterator != null ) responseIterator.next();
				
		var channelsIterator = responseIterator.next().elementsNamed("channel");
				
		while (channelsIterator.hasNext()) 
		{
			var channelXml = channelsIterator.next();
			
			
			var id 		: UInt	 = 0;
			var name 	: String = "";
			var link 	: String = "";
			var link_img : String = "";
			var desc	: String = "";
			var date 	: String = "";
			
			
			var attrIterator = channelXml.elements();
			
			while (attrIterator.hasNext()) 
			{
				var attribute = attrIterator.next();
				var attrName = attribute.nodeName;
				var attrValue = attribute.firstChild().nodeValue;
				
				switch (attrName) 
				{
					case "id":			id = Std.parseInt(attrValue);
					case "name":		name = attrValue;
					case "link":		link = attrValue;
					case "link_img":    link_img = attrValue;
					case "description":	desc = attrValue;
					case "date":		date = attrValue;
				
				}				
			}
			
			var channel = new Channel(
										name, 
										link, 
										link_img,
										id, 
										desc, 
										date, 
										new Array<Item>()
									);
										
			channelsArray.push(channel);
		}		
		
		return channelsArray;
		trace(channelsArray);
	}
	
	public function parseID() : Array<Int>
	{
		var channelsArray = new Array<Int>();
				
		var responseIterator = xml.iterator();
		if(responseIterator != null ) responseIterator.next();
				
		var channelsIterator = responseIterator.next().elementsNamed("channel");
				
		while (channelsIterator.hasNext()) 
		{
			var channelXml = channelsIterator.next();
			
			var id 		: UInt	 = 0;
			
			
			var attrIterator = channelXml.elements();
			
			while (attrIterator.hasNext()) 
			{
				var attribute = attrIterator.next();
				var attrName = attribute.nodeName;
				var attrValue = attribute.firstChild().nodeValue;
				
				if (attrName == "id") 
				{
					id = Std.parseInt(attrValue);	
				}				
			}
			channelsArray.push(id);
		}		
		
		return channelsArray;
	}
}